import {
  ComposableMenu,
  MenuItemDefinition,
  rotateAnimation,
} from '@amcax/base';
import { RelationsMenuProps } from '@app-cad-env/nextcad/widgets/ContextMenu/DefaultContextMenu/RelationsDialog/types';
import { PartLeftPanelEvents } from '@app-cad-env/nextcad/widgets/LeftPanel/types';
import { invokeEditCommand } from '@app-cad/common/utils';
import { ctx2, userEvents } from '@app-cad/module';
import { Box3, Vector3 } from 'three-legacy';

export const MenuItemScrollToNode: MenuItemDefinition<RelationsMenuProps> = {
  id: 'scrollToNode',
  children: '滚动到设计树对象',
  disabled: ({ props: { selectedDxids } }) => selectedDxids.length > 1,
  onClick: ({ props: { documentObject } }) =>
    userEvents.emit(PartLeftPanelEvents.ScrollTo, documentObject.dxid),
};

export const MenuItemCenterOnCanvas: MenuItemDefinition<RelationsMenuProps> = {
  id: 'centerOnCanvas',
  children: '图形居中',
  onClick: () => {
    if (!ctx2.cadScene.assisGroup?.children?.length) {
      return;
    }

    const box = new Box3().setFromObject(ctx2.cadScene.assisGroup);
    const target = box.getCenter(new Vector3());

    const sceneSetup = ctx2.viewer.sceneSetup;

    const originInfo = sceneSetup['getOriginInfo']();

    const direction = new Vector3();
    sceneSetup.camera.getWorldDirection(direction);
    const distance = sceneSetup.camera.position.distanceTo(
      sceneSetup.trackballControls.target,
    );
    const cameraPos = target.clone().sub(direction.multiplyScalar(distance));

    const rotateInfo = {
      ...originInfo,
      cameraPos,
      target,
    };

    rotateAnimation(sceneSetup, originInfo, rotateInfo, 400).then(() => {
      sceneSetup.updateControlsAndHelpers();
      ctx2.viewer.requestRender();
    });
  },
};

export const MenuItemInvokeCommand: MenuItemDefinition<RelationsMenuProps> = {
  id: 'invokeCommand',
  children: '编辑',
  disabled: ({ props: { selectedDxids } }) => selectedDxids.length > 1,
  onClick: ({ props: { documentObject } }) => invokeEditCommand(documentObject),
};

export const RelationObjectItemCMenu = ({ id }: { id: string }) => {
  return (
    <ComposableMenu
      id={id}
      menuItems={[
        MenuItemScrollToNode,
        MenuItemCenterOnCanvas,
        MenuItemInvokeCommand,
      ]}
    />
  );
};
